package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.ExportProduct;
import cn.itcast.domain.cargo.ExportProductExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.util.BeanMapUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.*;

@Controller
@RequestMapping("/cargo/export")
@Slf4j
public class PdfController extends BaseController {

    /**
     * 导出PDF (1) 入门案例
     * http://localhost:8080/cargo/export/exportPdf.do?id=2
     */
    @RequestMapping("/exportPdf1")
    public void exportPdf1() throws Exception {
        //1. 获取jasper文件流
        InputStream in =
                session.getServletContext().getResourceAsStream("/jasper/test01.jasper");

        //2. 创建JasperPrint，用于往模板中填充数据
        // 参数1 pdf文件流
        // 参数2 数据填充的方式：以map方式填充
        // 参数3 数据填充的方式：以数据源的方式填充
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, new HashMap<>(), new JREmptyDataSource());

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }

    /**
     * 导出PDF (2) 填充数据：map填充
     */
    @RequestMapping("/exportPdf2")
    public void exportPdf2() throws Exception {
        //1. 获取jasper文件流
        InputStream in =
                session.getServletContext().getResourceAsStream("/jasper/test03_parameter.jasper");

        // 构造map，map的key必须要与模板中的Parameters参数名称一致
        Map<String, Object> map = new HashMap<>();
        map.put("userName", "jacky");
        map.put("deptName", "开发部");
        map.put("email", "邮箱");
        map.put("companyName", "企业名称");

        //2. 创建JasperPrint，用于往模板中填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, map, new JREmptyDataSource());

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }

    @Autowired
    private DataSource dataSource;

    /**
     * 导出PDF (3) 数据填充 数据源 A JDBC
     */
    @RequestMapping("/exportPdf3")
    public void exportPdf3() throws Exception {
        //1. 获取jasper文件流
        InputStream in =
                session.getServletContext().getResourceAsStream("/jasper/test04_jdbc.jasper");

        //2. 创建JasperPrint，用于往模板中填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, null, dataSource.getConnection());

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * 导出PDF (4) 数据填充 数据源 B javabean
     */
    @RequestMapping("/exportPdf4")
    public void exportPdf4() throws Exception {
        //1. 获取jasper文件流
        InputStream in =
                session.getServletContext().getResourceAsStream("/jasper/test05_javabean.jasper");

        // 构造集合，封装模板数据
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            User user = new User();
            user.setUserName("球球");
            user.setEmail("qiuqiu@export.com");
            user.setCompanyName("幼儿园");
            user.setDeptName("开发部");
            list.add(user);
        }

        // 构造数据源集合对象
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);
        //2. 创建JasperPrint，用于往模板中填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, null, dataSource);

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * 导出PDF (5) 分组报表
     */
    @RequestMapping("/exportPdf6")
    public void exportPdf6() throws Exception {
        //1. 获取jasper文件流
        InputStream in =
                session.getServletContext().getResourceAsStream("/jasper/test06_group.jasper");

        // 构造集合，封装模板数据
        List<User> list = new ArrayList<>();
        for (int j = 1; j < 3; j++) {
            for (int i = 0; i < 5; i++) {
                User user = new User();
                user.setUserName("球球");
                user.setEmail("qiuqiu@export.com");
                user.setCompanyName("传智播客" + j);
                user.setDeptName("开发部");
                list.add(user);
            }
        }

        // 构造数据源集合对象
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);
        //2. 创建JasperPrint，用于往模板中填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, null, dataSource);

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * 导出PDF (7) 图形报表导出
     */
    @RequestMapping("/exportPdf7")
    public void exportPdf7() throws Exception {
        //1. 获取jasper文件流
        InputStream in =
                session.getServletContext().getResourceAsStream("/jasper/test07_chart.jasper");

        // 构造集合，封装模板数据
        List<Map<String,Object>> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Map<String,Object> map = new HashMap<>();
            map.put("title","厂家"+i);
            map.put("value",new Random().nextInt(100));
            list.add(map);
        }

        // 构造数据源集合对象
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);
        //2. 创建JasperPrint，用于往模板中填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, null, dataSource);

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    /**
     * 导出报运详情 (最终实现需求)
     */
    @RequestMapping("/exportPdf")
    public void exportPdf(String id) throws Exception {
        //1. 获取jasper文件流
        InputStream in =
                session.getServletContext().getResourceAsStream("/jasper/export.jasper");

        //第一步：根据报运单id查询报运单
        Export export = exportService.findById(id);
        // 对象转换为map集合（调用工具类）
        Map<String, Object> map = BeanMapUtils.beanToMap(export);

        //第二步：根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> productList = exportProductService.findAll(example);

        // 构造数据源集合对象
        JRDataSource dataSource = new JRBeanCollectionDataSource(productList);
        //2. 创建JasperPrint，用于往模板中填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, map, dataSource);

        //3. 导出PDF
        response.setHeader("content-disposition","attachment;fileName=export.pdf");
        ServletOutputStream out = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, out);
        out.close();
    }
}